package com.ming.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ming.anno.Log;
import com.ming.domain.SysUser;
import com.ming.sevice.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

/**
 * @Author:何元才
 * @Desc:
 * @data:2021-03-31 20:41
 */
@RestController
@Api(tags = "后台用户的接口")
@RequestMapping("/sys/user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 获取当前登录用户的信息
     *
     * @return
     */
    @GetMapping("info")
    @ApiOperation(value = "获取当前登陆用户的信息")
    @Log(operation = "获取当前登陆用户的信息")
    public ResponseEntity<SysUser> getUserInfo(){
        //获取当前用户
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        SysUser sysUser = sysUserService.getById(Long.valueOf(userId));
        return ResponseEntity.ok(sysUser);
    }

    @GetMapping("page")
    @ApiOperation("分页查询后台管理员的接口")
    @PreAuthorize("hasAuthority('sys:user:page')")
    @Log(operation = "分页查询后台管理员的接口")
    public ResponseEntity<Page<SysUser>> loadSysUserPage(Page<SysUser> page,SysUser sysUser){
        Page<SysUser> sysUserPage =  sysUserService.findSysUserByPage(page, sysUser);
        return ResponseEntity.ok(sysUserPage);
    }


    /**
     * 新增后台管理员
     *
     * @param sysUser
     * @return
     */
    @PostMapping
    @ApiOperation("新增后台管理员")
    @PreAuthorize("hasAuthority('sys:user:save')")
    @Log(operation = "新增后台管理员")
    public ResponseEntity<Void> addSysUser(@RequestBody SysUser sysUser){
        // 新增管理员 需要知道这个操作是谁做的
        String createUserId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        sysUser.setCreateUserId(Long.valueOf(createUserId));
        //调用service 做新增
        sysUserService.save(sysUser);
        return ResponseEntity.ok().build();
    }
}
